// com/zbo/servlet/UserInfoServlet.java
package com.zbo.servlet;

import com.alibaba.fastjson2.JSONObject;
import com.zbo.mapper.StudentMapper;
import com.zbo.service.StudentService;
import com.zbo.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user-info")
public class UserInfoServlet extends HttpServlet {
    private final StudentService studentService = new StudentService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        try {
            HttpSession session = req.getSession();
            Integer studentId = (Integer) session.getAttribute("studentId");
            if (studentId == null) {
                sendError(out, "未登录");
                return;
            }

            try (SqlSession sessionSql = SqlSessionFactoryUtils.getSqlSessionFactory().openSession()) {
                StudentMapper mapper = sessionSql.getMapper(StudentMapper.class);
                String username = mapper.selectUsernameById(studentId);
                if (username == null) {
                    sendError(out, "用户不存在");
                    return;
                }

                JSONObject res = new JSONObject();
                res.put("success", true);
                res.put("username", username);
                out.print(res.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
            sendError(out, "获取用户信息失败");
        } finally {
            out.flush();
        }
    }

    private void sendError(PrintWriter out, String msg) {
        JSONObject res = new JSONObject();
        res.put("success", false);
        res.put("message", msg);
        out.print(res.toJSONString());
    }
}